﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Infrastructure.Persistence;
using Universum.Model.Domain.Classes;
using Universum.Infrastructure.Persistence.Queries.MyClasses;
using System.Security.Principal;
using Universum.Model.Domain.MyClasses;

namespace Universum.Model.Services.MyClasses
{
	public class SignupServiceImpl : ISignupService
	{
		IRepository _Repository;
		IPrincipal _Principal;
		public SignupServiceImpl(IRepository repository,
			IPrincipal principal)
		{
			_Repository = repository;
			_Principal = principal;
		}
		#region ISignupService Members

		public void SignUpFor(Guid classId)
		{
			var @class = _Repository.Load<Class>(classId);
			if (@class.IsNull()) return;
			var previousSignups = _Repository.Query(new SignupByClassIdAndUsername(classId, _Principal.Identity.Name)).Count();
			if (@class != null && previousSignups == 0)
			{
				var newSignup = new Signup
				{
					Username = _Principal.Identity.Name,
					ClassId = classId,
					ID = Guid.NewGuid()
				};
				_Repository.SaveOrUpdate(newSignup);
			}
		}

		#endregion

		#region ISignupService Members


		public IList<Class> SignedForClasses()
		{
			var signups = _Repository.Query(new SignupByUsername(_Principal.Identity.Name)).ToList();
			var classes = new List<Class>();
			foreach (var item in signups)
			{
				var @class = _Repository.Load<Class>(item.ClassId);
				if (@class != null)
					classes.Add(@class);
				else
					_Repository.Remove(item);
			}
			return classes;
		}

		public IList<Class> UnSignedForClasses()
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
